/**
 * Light-commons Project
 * http://light-commons.googlecode.com
 * Copyright (C) 2008 Jason Green
 * email: guileen@gmail.com
 *
 * License: Apache License 2.0 
 * (http://www.apache.org/licenses/LICENSE-2.0)
 *
 */
package org.lightmtv.response;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.lightcommons.logger.Log;
import org.lightcommons.logger.LogFactory;
import org.lightcommons.util.Assert;

/**
 * @author gl
 * @since Jun 24, 2008
 */
public abstract class AbstractResponse implements Response {
	
	private static final Log log = LogFactory.getLog(AbstractResponse.class);
	private LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
	private boolean noCache=true;
	private List<Cookie> cookies=new ArrayList<Cookie>();
	
	public void setNoCache(boolean noCache) {
		this.noCache = noCache;
	}
	
	public boolean isNoCache() {
		return noCache;
	}
	
	public void setHeader(String name, String value) {
		map.put(name, value);
	}
	
	public Map<String, String> getHeaders() {
		return Collections.unmodifiableMap(map);
	}
	
	public void addCookie(Cookie cookie) {
		cookies.add(cookie);
	}
	
	public void send(HttpServletResponse response) {
		Assert.notNull(response,"response is required,it can not be null");
		try {
			for(Map.Entry<String, String> e:map.entrySet()){
				response.setHeader(e.getKey(), e.getValue());
			}
			if(noCache){
				response.addHeader("Pragma","No-cache");
				response.addHeader("Cache-Control","no-cache");
				response.addDateHeader("Expires",-1);
			}
			if(cookies!=null){
				for(Cookie cookie : cookies)
					response.addCookie(cookie);
			}
			sendQuietly(response);
		} catch (Exception e) {
			log.error(e);
		}
	}

	protected abstract void sendQuietly(HttpServletResponse response)throws Exception;
}
